package cn.zymall.app.controller.address;

import cn.zymall.app.service.AddressService;
import cn.zymall.app.service.CityViewService;
import cn.zymall.app.service.impl.AddressServiceImpl;
import cn.zymall.common.controller.crud.BaseController;
import cn.zymall.common.model.CityView;
import cn.zymall.common.model.ShippingAddress;
import cn.zymall.common.utils.response.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author xuxianda
 * @Description: 地址控制器
 * @date 2020/8/27 14:48
 * @Copyright
 * @return
 **/
@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @Autowired
    private CityViewService cityViewService;

    @GetMapping
    public HttpResult select(ShippingAddress shippingAddress) {
        if (shippingAddress == null) {
            return new HttpResult().fail("参数不能为空");
        }
        return addressService.select(shippingAddress);
    }

    @DeleteMapping
    public HttpResult remove(@RequestBody ShippingAddress shippingAddress) {
        if (shippingAddress == null) {
            return new HttpResult().fail("参数不能为空");
        }
        return addressService.remove(shippingAddress);
    }

    @PostMapping
    public HttpResult insert(@RequestBody ShippingAddress shippingAddress) {
        try {
            System.out.println(shippingAddress);
            CityView cityView = new CityView();
            cityView.setDistrictsCode(shippingAddress.getDistrict().toString());
            cityView = cityViewService.getByDistrict(cityView);
            if (cityView == null) {
                return new HttpResult().fail("没有这个县或区");
            }
            if (shippingAddress == null) {
                return new HttpResult().fail("areaCode参数不能为空");
            }
            shippingAddress.setCity(Integer.parseInt(cityView.getCityCode()));
            shippingAddress.setProvince(Integer.parseInt(cityView.getProvinceCode()));
            return addressService.insert(shippingAddress);
        } catch (Exception e) {
            e.printStackTrace();
            return new HttpResult().fail("添加失败，请重试");
        }
    }

    @PutMapping
    public HttpResult update(@RequestBody ShippingAddress shippingAddress) {
        if (shippingAddress == null) {
            return new HttpResult().fail("参数不能为空");
        }
        return addressService.update(shippingAddress);
    }
}
